package com.irdstudio.efp.console.service.boot;

import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.ExtensionLoader;
import com.alibaba.dubbo.common.utils.ConfigUtils;
import com.alibaba.dubbo.container.Container;
import com.alibaba.dubbo.container.Main;
import com.alibaba.dubbo.container.spring.SpringContainer;

/**
 * Dubbo服务启动入口
 * 
 * @author common
 * @version 2018-11-29
 */
public class DubboServiceMain {
	private static volatile boolean running = true;
	private static final Logger logger = LogManager.getLogger(DubboServiceMain.class);
	private static final String APPLICATION_CONTEXT_PATH = "classpath*:spring/applicationContext.xml";

	public static void main(String[] args) {
		System.setProperty(SpringContainer.SPRING_CONFIG, APPLICATION_CONTEXT_PATH);
		long startTime = System.currentTimeMillis();
		final ExtensionLoader<Container> loader = ExtensionLoader.getExtensionLoader(Container.class);

		try {
			String config = ConfigUtils.getProperty(Main.CONTAINER_KEY, loader.getDefaultExtensionName());
			String containerNames[] = Constants.COMMA_SPLIT_PATTERN.split(config);

			final List<Container> containers = new ArrayList<Container>();
			for (int i = 0; i < containerNames.length; i++) {
				containers.add(loader.getExtension(containerNames[i]));
			}

			logger.debug("Dubbo  stopped!");

			Runtime.getRuntime().addShutdownHook(new Thread() {
				@Override
				public void run() {
					for (Container container : containers) {
						try {
							container.stop();
							logger.debug("Dubbo " + container.getClass().getSimpleName() + " stopped!");
						} catch (Throwable t) {
							logger.error(t.getMessage(), t);
						}
						synchronized (DubboServiceMain.class) {
							running = false;
							DubboServiceMain.class.notify();
						}
					}
				}
			});

			for (Container container : containers) {
				container.start();
				logger.info("Dubbo " + container.getClass().getSimpleName() + " started!");
			}

			long elasticsTime = System.currentTimeMillis() - startTime;
			String startedMsg = "efp-console-service" + " started, elapsedTime=" + elasticsTime / 1000.0 + "s";
			logger.info(startedMsg);

		} catch (RuntimeException e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			System.exit(1);
		}

		synchronized (DubboServiceMain.class) {
			while (running) {
				try {
					DubboServiceMain.class.wait();
				} catch (Throwable e) {
					logger.error(e.getMessage(), e);
				}
			}
		}
	}

}
